package com.imay.live.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.base.util.StringUtil;
import com.imay.cocos.IMayCocos;
import com.imay.cocos.IMayCocosNetManager;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.fragment.room.MusicSelectFragment;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.manager.LocalMusicManager;
import com.imay.live.manager.MusicDownLoadManager;
import com.imay.live.manager.SensitiveWordFilterManager;
import com.imay.live.media.LivePusher;
import com.imay.live.model.MusicModel;
import com.imay.live.model.ShortLiveInfoModel;
import com.imay.live.model.TopicModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.proto.room.ShortLivePushResp;
import com.imay.live.proto.user.UserInfoCard;
import com.imay.live.utils.SimpleMediaPlayerUtil;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.custom.ChallengeView;
import com.imay.live.view.custom.RoomBaseView;
import com.imay.live.view.custom.RoomPushShortView;
import com.imay.live.view.custom.StartLiveShortCustomView;
import com.imay.live.view.custom.StartLiveShortView;
import com.imay.live.view.custom.StartLiveView;
import com.imay.live.R;

import java.io.File;

/**
 * Created by jeaman on 2017/6/23.
 * 超短播推流
 */

public class RoomPushShortActivity extends RoomPushBaseActivity implements RoomPushShortView.OnPushActionListener, IMayCocosNetManager.OnCocosShortLiveListener, LivePusher.PushBGMListener, MusicDownLoadManager.DownloadStatuListener {
    private final static int STATUS_START = 1;  //开始
    private final static int STATUS_FINISH = 2;  //完成
    private final static int STATUS_CANCEL = 3;  //取消
    private final static int STATUS_ABORT = 4;  //放弃
    private final static String EXTRA_NAME_CHALLENGE_ID = "challenge_id";
    private final static String EXTRA_NAME_CUSTOM_CHALLENGE = "custom_challenge";

    private static long COUNT_DOWN_TIME = 30000;    //30秒倒计时

    private long mShortLiveId;
    private boolean mShowChallenge;
    private int mCountAbortLeft;
    private boolean mCountdownFinish;   //倒计时是否结束
    private int mChallengeStatus;    //挑战状态
    private int mCocosCountdownSpeed = 1;
    private boolean mStartLiveRequesting;   //是否正在请求
    private MusicSelectFragment musicSelectFragment;
    private boolean isPlaying;
    private String deflautMusic;
    private StartLiveShortView startLiveShortView;
    private StartLiveShortCustomView mStartLiveShortCustomView;
    private boolean mCustomChallenge;   //是否自己出题
    private String musicUrl;
    private int mChallengeId;


    public static void startActivity(Context context) {
        startActivity(context, false, 0);
    }

    public static void startActivity(Context context, boolean customChallenge) {
        startActivity(context, customChallenge, 0);
    }

    public static void startActivity(Context context, int challengeId) {
        startActivity(context, false, challengeId);
    }

    public static void startActivity(Context context, boolean customChallenge, int challengeId) {
        Intent intent = new Intent(context, RoomPushShortActivity.class);
        intent.putExtra(EXTRA_NAME_CUSTOM_CHALLENGE, customChallenge);
        intent.putExtra(EXTRA_NAME_CHALLENGE_ID, challengeId);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_push;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mChallengeId = getIntent().getIntExtra(EXTRA_NAME_CHALLENGE_ID, 0);
        mCustomChallenge = getIntent().getBooleanExtra(EXTRA_NAME_CUSTOM_CHALLENGE, false);
        super.initView(savedInstanceState);

        initRoomView();
        addRoomView(0);  //添加CocosView时会黑屏，提前添加避免中途黑屏
        getRoomView().hideAllViewWithoutCocos();

        mLivePusher.setPushBGMListener(this);
        if (!mCustomChallenge) {
            getTopicInfo(); //先获取题目
        }
        MobclickAgent.onEvent(this, "cdb_ready_open");
    }

    @Override
    protected StartLiveView createStartLiveView() {
        if (mCustomChallenge) {
            mStartLiveShortCustomView = new StartLiveShortCustomView(this);
            mStartLiveShortCustomView.setOnActionClickListener(this);
            mStartLiveShortCustomView.attachKeyboard(this);
            return mStartLiveShortCustomView;
        } else {
            startLiveShortView = new StartLiveShortView(this);
            startLiveShortView.setOnActionClickListener(this);
            return startLiveShortView;
        }
    }

    private RoomPushShortView getRoomView() {
        return (RoomPushShortView) mRoomView;
    }

    @Override
    protected int getWatermark() {
        return R.mipmap.ico_03_chaodanbo;
    }

    @Override
    protected RoomBaseView createRoomView() {
        RoomPushShortView roomView = new RoomPushShortView(this);
        roomView.setOnPushActionListener(this);
        return roomView;
    }

    @Override
    protected void requestStartLive() {
        if (mCustomChallenge) {
            requestSetChallenge();
        } else {
            requestStartChallenge();
        }
    }

    private void requestStartChallenge() {
        if (mStartLiveRequesting) { //防止重复点击
            return;
        }
        mStartLiveRequesting = true;
        String city = "";
        double latitude = 0;
        double longitude = 0;
        if (mShowLocation) {
            city = mCity;
            latitude = mLatitude;
            longitude = mLongitude;
        }
        ProtoRequestHelper.task(ProtoHttpFactory.requestStartShortLive(city, latitude, longitude, mChallengeId)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                mStartLiveRequesting = false;
                Result<ShortLivePushResp> result = JSON.parseObject(data, new TypeReference<Result<ShortLivePushResp>>() {
                }.getType());
                if (result.result == ResultCode.CodeSuccess && result.data != null) {
                    mChallengeStatus = STATUS_START;    //开始
                    mCountAbortLeft = result.data.getCountAbortLeft();
                    mShortLiveId = result.data.getShortLiveInfo().getShortLiveId();
                    startLive(result.data.getHostesInfo(), result.data.getPushStreamUrl(), result.data.getShortLiveInfo());
                    IMayCocos.enterRoomByShortLivePush(mShortLiveId, JSON.toJSONString(result.data));    //注意：先添加cocos才能调用cocos的方法
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                mStartLiveRequesting = false;
                processStartLiveErrorCode(code);
            }
        });
    }

    private void processStartLiveErrorCode(int code) {
        if (code == ResultCode.CodeUserRealNameVerifiedNotExist || code == ResultCode.CodeUserRealNameVerifieding) {    //未实名认证
            needRealNameAuth();
        } else if (code == ResultCode.CodeShortLiveGiveUpLimit) {
            DialogFragmentHelper.showTipsDialog(getSupportFragmentManager(), getString(R.string.short_live_push_abort_limit), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MobclickAgent.onEvent(RoomPushShortActivity.this, "cdb_ready_get");
                }
            });
        } else if (code == ResultCode.CodeShortLiveChallengeLimit) {
            DialogFragmentHelper.showTipsDialog(getSupportFragmentManager(), getString(R.string.short_live_push_today_limit));
        } else if (code == ResultCode.CodeShortLiveNoMoreChallenge) {
            DialogFragmentHelper.showTipsDialog(getSupportFragmentManager(), getString(R.string.short_live_push_no_more));
        } else {
            ErrorResult.toastError(RoomPushShortActivity.this, code);
        }
    }

    private void requestSetChallenge() {
        String nick = UserInfoCache.getNick();
        String title = mStartLiveShortCustomView.getTitle();
        String content = mStartLiveShortCustomView.getContent();
        mStartLiveShortCustomView.hideKeyboard();
        if (SensitiveWordFilterManager.getInstance().hasSensitiveWord(title)) {
            ToastUtil.show(this, R.string.live_sensitive_challenge_title);
            return;
        }
        if (SensitiveWordFilterManager.getInstance().hasSensitiveWord(content)) {
            ToastUtil.show(this, R.string.live_sensitive_challenge_content);
            return;
        }
        ProtoRequestHelper.task(ProtoHttpFactory.requestSetChallenge(nick, title, content, mChallengeId)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                Result<TopicModel> result = JSON.parseObject(data, new TypeReference<Result<TopicModel>>() {
                }.getType());
                if (result.result == ResultCode.CodeSuccess && result.data != null) {
                    if (result.data.getId() > 0) {
                        mChallengeId = result.data.getId();
                        requestStartChallenge();
                    }
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                processStartLiveErrorCode(code);
            }
        });
    }

    protected void startLive(UserInfoCard userInfoCard, String pushUrl, ShortLiveInfoModel shortLiveInfo) {
        setPushUrl(pushUrl);
        setRoomId(userInfoCard.roomId);
        setAnchorInfo(userInfoCard);
        mShortLiveId = shortLiveInfo.getShortLiveId();
        setShortLivePushBGM();

        showChallenge(shortLiveInfo.getChallengeTitle(), shortLiveInfo.getChallengeContent(), shortLiveInfo.getAuthorName());
        startPublishRtmp();

        setRoomAnchorInfo();
        //显示挑战题目
        getRoomView().setChallengeTitle(shortLiveInfo.getChallengeTitle());
        getRoomView().setChallengeContent(shortLiveInfo.getChallengeContent());
        getRoomView().setChallengeContentVisibility(true);
    }

    private void showChallenge(String title, String content, String author) {
        if (mShowChallenge) {
            return;
        }
        mShowChallenge = true;

        removeStartLiveView();

        final ChallengeView challengeView = new ChallengeView(this);
        challengeView.setTitle(title);
        challengeView.setContent(content);
        challengeView.setAuthor(author);
        challengeView.setCountDownTimerListener(new ChallengeView.CountDownTimerListener() {
            @Override
            public void onFinish() {
                if (!isDestroyed()) {
                    mContainerView.removeView(challengeView);
                    getRoomView().showAllView();
                    getRoomView().startCountDown(COUNT_DOWN_TIME);
                    IMayCocos.showShortLiveCountDown(mCocosCountdownSpeed);
                }
            }
        });
        mContainerView.addView(challengeView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    }

    //结束挑战
    private void requestFinishShortLive() {
        stopPublishRtmp();
        DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), null);
        ProtoRequestHelper.task(ProtoHttpFactory.requestFinishShortLive(mShortLiveId)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                mChallengeStatus = STATUS_FINISH;   //结束
                if (!isDestroyed()) {
                    DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                    IMayCocosNetManager.getInstance().addOnCocosShortLiveListener(RoomPushShortActivity.this);    //监听挑战完成动画结束时间
                    IMayCocos.showShortLiveEnd();
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                ToastUtil.show(RoomPushShortActivity.this, R.string.short_live_challenge_server_error);
                closeShortLive();
            }
        });
    }

    //放弃挑战
    private void requestAbortShortLive() {
        mChallengeStatus = STATUS_ABORT;
        ProtoRequestHelper.task(ProtoHttpFactory.requestAbortShortLive(mShortLiveId)).setTag(this.hashCode()).request(null);
    }

    //取消挑战
    private void requestCancelShortLive() {
        mChallengeStatus = STATUS_CANCEL;
        ProtoRequestHelper.task(ProtoHttpFactory.requestCancelShortLive(mShortLiveId)).setTag(this.hashCode()).request(null);
    }

    private void closeShortLive() {
        IMayCocosNetManager.getInstance().removeOnCocosShortLiveListener(this);
        if (!isDestroyed()) {
            onBackPressed();
            RoomLiveShortActivity.startActivity(RoomPushShortActivity.this);
        }
    }

    private void closeCocosCountdown() {
        IMayCocos.closeAllEffect(); //关闭cocos转圈
    }

    //结束直播
    @Override
    protected void requestEndLive() {
        cocosExitRoom();
        stopPublishRtmp();
        requestAbortShortLive();    //放弃挑战
    }

    @Override
    protected void setLinkMicNumber(int number) {

    }

    @Override
    protected void onLocationSuccess() {

    }

    @Override
    public void onResume() {
        super.onResume();
        if (mChallengeStatus == STATUS_CANCEL) { //切回前台时，如果取消挑战，toast并切换到观众
            ToastUtil.show(this, R.string.short_live_challenge_failed);
            closeShortLive();
        }
        MobclickAgent.onResume(this);
    }

    @Override
    public void onStop() {
        if (!mCountdownFinish && mChallengeStatus == STATUS_START) { //倒计时未结束进入后台，统一当挑战失败
            getRoomView().cancelCountDown();
            closeCocosCountdown();
            requestCancelShortLive();
            stopPublishRtmp();
            getRoomView().setPlayViewVisible(false);

        }
        super.onStop();
    }

    @Override
    public void onBackPressed() {
        if (mChallengeStatus == STATUS_START && mStartPush && !mShowExitConfirm) {
            DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(),
                    getString(R.string.short_live_push_abort_dialog_title),
                    getString(R.string.short_live_push_abort_dialog_message, mCountAbortLeft),
                    getString(R.string.short_live_push_abort_dialog_positive),
                    getString(R.string.short_live_push_abort_dialog_negative),
                    true,
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mShowExitConfirm = true;
                            requestEndLive();
                            onBackPressed();
                            MobclickAgent.onEvent(RoomPushShortActivity.this, "cdb_challenge_giveup");
                        }
                    },
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            MobclickAgent.onEvent(RoomPushShortActivity.this, "cdb_challenge_nevergiveup");
                        }
                    });
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void cocosExitRoomByType() {
        IMayCocos.exitRoomByShortLivePush(mShortLiveId);
    }

//    @Override
//    public void onGameClick() {
//        showGame();
//    }

    @Override
    public void onGiftClick() {
        onCocosChooseUserClick();
    }

    @Override
    public void onMusicClick() {
        if (isPlaying) {
            mLivePusher.pauseBGM();
            getRoomView().setMusicViewAnim(false);
            isPlaying = false;
        } else {
            mLivePusher.resumeBGM();
            getRoomView().setMusicViewAnim(true);
            isPlaying = true;
        }


    }



    @Override
    public void onCameraClick() {
        switchCamera();
    }

    @Override
    public void onBeautyClick() {
        showBeautyView();
    }

    @Override
    public void onBGMClick() {
        if (musicSelectFragment == null) {
            musicSelectFragment = MusicSelectFragment.newInstance();
        }
        DialogFragmentHelper.showDialogFragment(getSupportFragmentManager(), musicSelectFragment);
    }

    @Override
    public void onCountdownFinish() {
        mCountdownFinish = true;
        requestFinishShortLive();
        closeCocosCountdown();
        getRoomView().setPlayViewVisible(false);

    }

    @Override
    public void onCountdownTick(long millisUntilFinished) {
        //调整cocos转圈动画速度
        int speed = 0;
        if (millisUntilFinished > 20000) {
            speed = 1;
        } else if (millisUntilFinished > 10000) {
            speed = 2;
        } else if (millisUntilFinished > 5000) {
            speed = 4;
        } else {
            speed = 6;
        }
        if (speed > 0 && mCocosCountdownSpeed != speed) {
            mCocosCountdownSpeed = speed;
            IMayCocos.showShortLiveCountDown(mCocosCountdownSpeed);
        }
    }

    @Override
    public void onCocosEndShortLiveFinish() {
        closeShortLive();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private void setShortLivePushBGM() {
        if (musicSelectFragment != null && !StringUtil.isEmpty(musicSelectFragment.getSelectFilePath())) {
            mLivePusher.setBGM(musicSelectFragment.getSelectFilePath());
        }else if (!StringUtil.isEmpty(deflautMusic)){
            mLivePusher.setBGM(new File(LocalMusicManager.musicDownLoadPath,deflautMusic).getPath());
        }
    }

    @Override
    public void onDestroy() {
        SimpleMediaPlayerUtil.getInstance().release();
        super.onDestroy();
    }

    @Override
    public void onPlayBGMSuccess() {
        getRoomView().setPlayViewVisible(true);
        getRoomView().setMusicViewAnim(true);
        isPlaying = true;
    }



    private void getTopicInfo() {
        ProtoRequestHelper.task(ProtoHttpFactory.getTopic(mChallengeId)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                Result<TopicModel> result = JSON.parseObject(data, new TypeReference<Result<TopicModel>>() {
                }.getType());
                if (result.result == ResultCode.CodeSuccess && result.data != null) {
                    if (mChallengeId !=0){
                        startLiveShortView.setViewByType(result.data);
                    }else{
                        mChallengeId = result.data.getId();
                    }
                    musicUrl = result.data.getMusicUrl();
                    if (!StringUtil.isEmpty(musicUrl)) {
                        downloadMusic(musicUrl,result.data.getDefMusicId(),result.data.getMusicUpdateTime());
                    }else{
                        startLiveShortView.setButtonStatus(StartLiveShortView.STATUS_COMPLETE);
                    }
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), getString(R.string.load_again), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getTopicInfo();
                    }
                });
            }
        });
    }

    @Override
    public void onDownloadSuccess(long id) {
        startLiveShortView.setButtonStatus(StartLiveShortView.STATUS_COMPLETE);
    }

    @Override
    public void onDownloadFail(long id) {
        MusicDownLoadManager.getInstance().cancle(id);
        DialogFragmentHelper.showConfirmDialog(getSupportFragmentManager(), getString(R.string.load_again), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicDownLoadManager.getInstance().createDownLoadRequset(musicUrl, deflautMusic);
            }
        });
    }

    private void downloadMusic(String musicUrl,int musicId,int musicTime){
        deflautMusic = MusicModel.getMucicName(musicId, musicTime);
        if (!LocalMusicManager.getInstance().checkMusicExist(deflautMusic)) {
            MusicDownLoadManager.getInstance().setDownloadStatuListener(RoomPushShortActivity.this);
            MusicDownLoadManager.getInstance().createDownLoadRequset(musicUrl, deflautMusic);
        }else{
            startLiveShortView.setButtonStatus(StartLiveShortView.STATUS_COMPLETE);
        }
    }

    @Override
    public void onUserHeadClick(UserInfoCard userInfoCard) {

    }
}
